using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

namespace EntityKit.Runtime
{
    public static partial class AudioKit
    {
        public static float MultipleVolume
        {
            get => multipleVolume;
            set
            {
                multipleVolume = Mathf.Clamp01(value);
                foreach (var source in multipleSources)
                {
                    if (source != null) source.volume = multipleVolume;
                }
            }
        }

        public static bool MultipleMute
        {
            get => isMultipleSoundMute;
            set
            {
                if (isMultipleSoundMute == value) return;
                isMultipleSoundMute = value;
                foreach (var source in multipleSources)
                {
                    if (source != null) source.mute = value;
                }
            }
        }


        public static void PlayMultipleSound(AudioClip clip, bool isLoop = false, float speed = 1)
        {
            if (!isInitialized || !ValidateClip(clip)) return;

            var source = GetAvailableMultipleSource();
            if (source == null) return ;

            ConfigureAudioSource(source, clip, isLoop, speed);
            source.volume = multipleVolume;
            source.mute = isMultipleSoundMute;
            source.Play();
        }


        /// <summary>
        /// 停止所有多声道音效
        /// </summary>
        public static void StopAllMultipleSound()
        {
            foreach (var source in multipleSources)
            {
                if (source != null)
                {
                    source.Stop();
                    // 将所有停止的源添加回可用队列
                    availableMultipleSources.Enqueue(source);
                }
            }
        }

        private static AudioSource GetAvailableMultipleSource()
        {
            // 查找可用的音频源
            if (availableMultipleSources.Count > 0)
            {
                var source = availableMultipleSources.Dequeue();
                if (source != null)
                    return source;
            }

            // 如果达到最大声道数，替换最旧的音频源
            if (multipleSources.Count >= maxMultipleChannels)
                return ReplaceOldestMultipleSource();

            // 创建新的音频源
            var newSource = CreateAudioSource($"Multiple_{multipleSources.Count}", multipleVolume, 1, 0, root, isMultipleSoundMute);
            multipleSources.Add(newSource);
            return newSource;
        }

        private static AudioSource ReplaceOldestMultipleSource()
        {
            if (multipleSources.Count <= 0) return null;

            var oldest = multipleSources[0];
            multipleSources.RemoveAt(0);

            // 从可用队列中移除被替换的源（如果存在）
            var tempQueue = new Queue<AudioSource>();
            while (availableMultipleSources.Count > 0)
            {
                var source = availableMultipleSources.Dequeue();
                if (source != oldest)
                    tempQueue.Enqueue(source);
            }

            availableMultipleSources.Clear();
            while (tempQueue.Count > 0)
                availableMultipleSources.Enqueue(tempQueue.Dequeue());

            if (oldest != null && oldest.gameObject != null)
                UnityEngine.Object.Destroy(oldest.gameObject);

            var newSource = CreateAudioSource($"Multiple_{multipleSources.Count}", multipleVolume, 1, 0, root, isMultipleSoundMute);
            multipleSources.Add(newSource);
            return newSource;
        }

        private static void MultipleSoundInitialize()
        {
            // 多声道音效的初始化在首次使用时进行
            MultipleVolume = multipleVolumeDefault;
        }

        private static void MultipleSoundUpdate()
        {
            // 检查正在播放的音频源，如果播放完成则将其添加回可用队列
            for (int i = multipleSources.Count - 1; i >= 0; i--)
            {
                var source = multipleSources[i];
                if (source != null && !source.isPlaying && !availableMultipleSources.Contains(source))
                {
                    availableMultipleSources.Enqueue(source);
                }
            }
        }

        private static void MultipleSoundRelease()
        {
            // 销毁所有多声道音效的音频源
            foreach (var source in multipleSources)
            {
                if (source != null)
                {
                    if (source.gameObject != null)
                        Object.Destroy(source.gameObject);
                }
            }

            multipleSources.Clear();
            availableMultipleSources.Clear();
        }

        private static float multipleVolumeDefault = 1;
        private static float multipleVolume;
        private static int maxMultipleChannels = 5;
        private static bool isMultipleSoundMute;
        private static readonly List<AudioSource> multipleSources = new List<AudioSource>();
        private static readonly Queue<AudioSource> availableMultipleSources = new Queue<AudioSource>();
    }
}